import { Button, Card, Table, Modal,message, Upload,Form,Input} from 'antd'
import "./index.css"
import { reqTrademarkPageList,addOrUpdate,removeTrademark } from '@/api/user'
import type { ColumnsType } from "antd/es/table";
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import { PlusOutlined, EditOutlined, DeleteOutlined, LoadingOutlined } from '@ant-design/icons'
import React, { useEffect, useState } from 'react'
import type { hospitalListData } from "@/api/user/model/userTypes"
import {TrademarkData} from "@/api/user/model/userTypes"
import { useForm } from "antd/lib/form/Form";

export default function HospitalList() {

  let [form] = useForm();

const columns:ColumnsType<any> = [
  {
    title: '序号',
    dataIndex: 'key',
    align: "center",
    render: (x:any, y:any, index: number) => {
      return index + 1;
    }
  },
  {
    title: '品牌名称',
    align: "center",
    dataIndex: 'tmName',
  },
  {
    title: '品牌LOGO',
    align: "center",
    dataIndex: 'logoUrl',
    render: (data: string) => {
      return <img width="70" src={data} alt="" />;
    },
  },
  {
    title: '操作',
    align: "center",
    render: (row:TrademarkData) => {
      return <div>
        <Button icon={<EditOutlined />} type="primary"
        //   onClick={() => {
        //   navigate(`/syt/hospital/hospitalSet/edit/${row.id}`)
        // }}
          onClick={()=>{
            addOrUpdaBrande(row)
          }}
        >修改</Button>
        <Button
           onClick={()=>{
            removeHospitalSet(row.id)
          }}
            className="ml" icon={<DeleteOutlined />} danger type="primary">删除</Button>
      </div>
    }
  },
];


  //声明状态
  let [page, setPage] = useState(1);
  let [limit, setLimit] = useState(3);
  let [total, setTotal] = useState(10);
  let [trademark, setTrademark] = useState({})
  let [hospital, setHospital] = useState<hospitalListData>([])
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();
  const [logoUrl, setLogoUrl] = useState();
  const [RowId,setRowID] = useState()
//发送请求
  useEffect(() => {
    getTrademarkPageList(page,limit)
  },[page,limit])
  
  //封装发送请求
  const getTrademarkPageList = async (page:number,limit:number) => {
    let result = await reqTrademarkPageList(page, limit)
   setPage(result.current)
   setLimit(result.size)
   setTotal(result.total)
    setHospital(result.records)
    // Object.assign(hospital,result.records)
  }
  



  const removeHospitalSet = async (id: any) => {
    try {
      await removeTrademark(id)
      if (hospital.length > 1) {
        setPage(page)
        getTrademarkPageList(page, limit)
      } else if(hospital.length === 1){
        page = page - 1
        setPage(page)
        getTrademarkPageList(page, limit)
      }
      message.success('删除成功')
    } catch (error) {
      message.error('删除失败')
    }
    
    
    
  }

  const addOrUpdaBrande = (row?: any) => {
    if (row) {
      form.setFieldsValue(row);
      setImageUrl((row).logoUrl);
      Object.assign(trademark,row)
      setLogoUrl(row.logoUrl)
      setRowID(row.id)
    } else {
      setTrademark({})
      form.resetFields()
      setImageUrl('');
    }
    setIsModalOpen(true);
  };

  // const handleOk = () => {
  //   setIsModalOpen(false);
  // };

  //声明函数 表单完成的事件回调
  let handleOk = async () => {
    if (Object.keys(trademark).length === 3) {
        let id = RowId
      let tmName = form.getFieldsValue().tmName
         Object.assign(trademark,{id,tmName,logoUrl})
      } else {
          let tmName = form.getFieldsValue().tmName
         Object.assign(trademark,{tmName,logoUrl})
         setTrademark({tmName,logoUrl})
      }
      try {
        if (Object.keys(trademark).length === 3) {
          await addOrUpdate(trademark)
          message.success("修改成功");
          getTrademarkPageList(page,limit)
        } else {
          await addOrUpdate(trademark)
          message.success('添加成功');
          getTrademarkPageList(1,limit)
        }
        setIsModalOpen(false);
      } catch (error) {
        message.error('添加失败')
        setIsModalOpen(false);
      }
      // addOrUpdate(trademark)
    //设置状态为加载中
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };




const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传图片</div>
    </div>
  );

  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    
    if (info.file.response) {
      console.log('change-->', info.file.response.data)
      setLogoUrl(info.file.response.data)
    }
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as RcFile, url => {
        setLoading(false);
        setImageUrl(url);
      });
    }
  };

const getBase64 = (img: RcFile, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

const beforeUpload = (file: RcFile) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};






//  const finish = (values: any) => {
//     console.log('Success:', values);
//   };

//   const onFinishFailed = (errorInfo: any) => {
//     console.log('Failed:', errorInfo);
//   };


const normFile = (e: any) => {
    console.log('Upload event:', e);
    if (Array.isArray(e)) {
        return e;
    }
    return e && e.fileList;
};





  return (
    <div className='cardContainer'>
      <Card style={{ width: 1024 }}>
         <Button type="primary" size="middle"  onClick={()=>{addOrUpdaBrande()}}>
          {<PlusOutlined />}  添加
        </Button>
      </Card>
      <Card bordered={true} style={{ width: 1024 }}>
        <Table
        dataSource={hospital}
        columns={columns}
        className="mt"
        bordered
        rowKey="id"
        pagination={{
        total: total, //总条数
        pageSize: limit, //每页显示的数量
        current: page, //当前页码
        showQuickJumper: true,
        showSizeChanger:true,
          pageSizeOptions: [2, 5, 10, 15], //调整每页显示的数量 数组
         showTotal: (total) => {
          return <span>总计 {total} 条</span>;
        },
        onChange: (page: number, pageSize: number) => {
          //修改当前页
          setPage(page);
          //修改每页显示数量
          setLimit(pageSize);
        }
      }}
      />
      </Card>
      <Modal width={600} className="addBrandeModal" title="添加品牌" visible={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          form= {form}
          initialValues={{ remember: true }}
          // onFinish={finish}
          // onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="品牌名称"
            name="tmName"
          className=" addBrande"
            rules={[{ required: true, message: '请输入品牌名称!' }]}
          >
            <Input className='brandeIpt'/>
          </Form.Item>

          <Form.Item
            label="品牌LOGO"
            name="logoUrl"
            className='upLoadImg'
            valuePropName="fileList"
            getValueFromEvent={normFile}
            rules={[{ required: true, message: '请上传图片' }]}
          >
            <Upload
              // name="avatar"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="/app-dev/admin/product/upload"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}




 